package com.ruicar.afs.cloud.basic.cms.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.archive.feign.ArchiveApiFeign;
import com.ruicar.afs.cloud.archive.utils.GetTokenConfig;
import com.ruicar.afs.cloud.basic.common.condition.QueryCustInfoMultipleCondition;
import com.ruicar.afs.cloud.basic.common.entity.BasicCustBaseInfo;
import com.ruicar.afs.cloud.basic.common.entity.BasicMainInfo;
import com.ruicar.afs.cloud.basic.common.entity.BasicRepaymentPlan;
import com.ruicar.afs.cloud.basic.common.service.BasicCustBaseInfoService;
import com.ruicar.afs.cloud.basic.common.service.BasicMainInfoService;
import com.ruicar.afs.cloud.basic.common.service.BasicRepaymentPlanService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.ContractStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.RepaymentStatusEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 合同主信息查询
 */
@Slf4j
@RestController
@RequestMapping("/ContractMainInfoToCms")
@AllArgsConstructor
public class IcosContractMainInfoController {

    private final BasicMainInfoService basicMainInfoService;
    private final BasicCustBaseInfoService basicCustBaseInfoService;
    private final BasicRepaymentPlanService basicRepaymentPlanService;
    private final ArchiveApiFeign archiveApiFeign;
    private final GetTokenConfig getTokenConfig;

    @ApiOperation(value = "查询合同状态")
    @PostMapping("/contractStatus")
    public IResponse<List<JSONObject>> contractStatus(@RequestParam(value = "contractNo",required = false) String contractNo){
        log.error("-------------------查询合同状态接口入参为:{}-------------------",contractNo);
        if(EmptyUtils.isEmpty(contractNo)){
            return new IResponse().fail("合同号码不能为空");
        }
        BasicMainInfo basicMainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>lambdaQuery().eq(BasicMainInfo::getContractNo, contractNo));
        QueryCustInfoMultipleCondition condition = new QueryCustInfoMultipleCondition();
        condition.setCustRole(AfsEnumUtil.key(PersonRoleTypeEnum.MAIN_PERSON));
        condition.setContractNo(contractNo);
        List list = basicCustBaseInfoService.findByCustInfo(condition);
        if(EmptyUtils.isEmpty(list)){
            log.info("-------------------没有查询到客户信息,查询到的数据为:{}-------------------",list);
            return new IResponse().fail("没有查询到客户信息");
        }
        BasicCustBaseInfo baseInfo = JSON.parseObject(JSON.toJSONString(list.get(0)),BasicCustBaseInfo.class);
        JSONObject mainInfo = JSON.parseObject(JSON.toJSONString(basicMainInfo));
        mainInfo.put("certNo",baseInfo.getCertNo());
        mainInfo.put("closeDate", EmptyUtils.isNotEmpty(basicMainInfo.getCloseDate())?DateUtil.format(basicMainInfo.getCloseDate(),"yyyy-MM-dd hh:mm:ss"):"");
        List<BasicRepaymentPlan> repaymentPlans = basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>lambdaQuery().eq(BasicRepaymentPlan::getContractNo, contractNo));
        int i = 0;
        for(BasicRepaymentPlan plan : repaymentPlans){
            if(RepaymentStatusEnum.REPAID.equals(plan.getStatus())){
                i++;
            }
        }
        if(ContractStatusEnum.contractEffective == basicMainInfo.getContractStatus()){
            if(i>6){
                mainInfo.put("contractStatus","2");
            }else{
                mainInfo.put("contractStatus","3");
            }
        }
        mainInfo.put("request_date",DateUtil.format(DateUtil.date(),"yyyy-MM-dd hh:mm:ss"));
        return new IResponse<List<JSONObject>>().setData(Arrays.asList(mainInfo));
    }

    @ApiOperation(value = "结清邮寄查询")
    @PostMapping("/settleExpressInquiry")
    public IResponse<JSONObject> settleExpressInquiry(@RequestParam(value = "contractNo",required = false) String contractNo,
                                                      @RequestParam(value = "certNo",required = false) String certNo){
        if((EmptyUtils.isEmpty(contractNo)||"null".equals(contractNo))&&(EmptyUtils.isEmpty(certNo)||"null".equals(certNo))){
            return new IResponse().fail("合同号码、证件号码不能同时为空");
        }
        if("null".equals(contractNo)){
            contractNo = null;
        }
        if("null".equals(certNo)){
            certNo = null;
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("clientId",getTokenConfig.getClientId());
        headers.put("clientSecret",getTokenConfig.getClientSecret());
        headers.put("grant_type",getTokenConfig.getGrantType());
        JSONObject jb = new JSONObject();
        jb.put("id_card",certNo);
        jb.put("application_no",contractNo);

        JSONObject dto = archiveApiFeign.settleExpress(jb, headers);

        if("1".equals(dto.getString("success"))){
            if(EmptyUtils.isEmpty(certNo)){
                QueryCustInfoMultipleCondition condition = new QueryCustInfoMultipleCondition();
                condition.setContractNo(contractNo);
                condition.setCustRole(AfsEnumUtil.key(PersonRoleTypeEnum.MAIN_PERSON));
                List list = basicCustBaseInfoService.findByCustInfo(condition);
                if(EmptyUtils.isEmpty(list)){
                    return new IResponse().fail("没有查询到客户信息");
                }
                BasicCustBaseInfo baseInfo = JSON.parseObject(JSON.toJSONString(list.get(0)), BasicCustBaseInfo.class);
                if(EmptyUtils.isEmpty(baseInfo)){
                    return new IResponse().fail("没有查询到客户信息");
                }
                certNo = baseInfo.getCertNo();
            }


            JSONArray jsonArray = dto.getJSONObject("data").getJSONArray("expressInfos");
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                jsonObject.put("case_status","1");
                jsonObject.put("id_card",certNo);
            }
            return new IResponse<JSONObject>().setData(dto);
        }

        return new IResponse<JSONObject>().fail("查询失败，没有查询到相关信息");
    }


}
